package cn.com.headfree.server.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gta.edu.sdk.common.dto.ResultData;

import cn.com.headfree.server.dto.ScpFile;
import cn.com.headfree.util.ScpclientUtil;

@CrossOrigin("*")
@RestController
@RequestMapping(value = "/scpfile", produces = "application/json;charset=UTF-8")
public class ScpController {
	// 日志
	private static final Logger log = Logger.getLogger(ScpController.class);

	/**
	 * @param response
	 * @param remotefile
	 * @return
	 */
	@GetMapping("/downloadFile")
	public void downloadFile(HttpServletResponse response, String fileName) {
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		OutputStream os = null;
		File file = null;
		try {
			String localTempFileName = ScpclientUtil.getInstance().downFile(fileName);
			// 设置响应头
			response.setHeader("content-type", "application/octet-stream");
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			// 实现文件下载
			byte[] buffer = new byte[1024];
			file = new File(localTempFileName);
			fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			os = response.getOutputStream();
			int i = bis.read(buffer);
			while (i != -1) {
				os.write(buffer, 0, i);
				i = bis.read(buffer);
			}
		} catch (Exception e) {
			log.error("download logfile fail!!", e);
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
				}
			}
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
				}
			}
			if (file.exists()) {
				file.delete();
			}
		}
	}

	/**
	 * 查询文件-默认全部查询,支持模糊查询
	 *
	 * @return
	 */
	@RequestMapping("/findFileList")
	public ResultData findFileList(String fileName) {
		ResultData resultData = new ResultData();
		try {
			List<ScpFile> list = ScpclientUtil.getInstance().getRemoteFileList(fileName);
			resultData.setData(list);
		} catch (Exception e) {
			resultData.setSuccess(false);
			resultData.setErrorMsg("业务处理出现了异常！！");
			log.error("查询远程日志目录出现了异常:", e);
		}
		return resultData;
	}

}
